package com.zwj.interview.BFS;

import java.util.LinkedList;
import java.util.Queue;

/**
 * @Author: Zwj
 * @Date: 2022/2/23 17:44
 */
public class 求树的最小高度 {

    //采用BFS（模板代码）
    public int minDepth(TreeNode root) {
        if (root == null) {
            return 0;
        }
        Queue<TreeNode> q = new LinkedList<TreeNode>();
        q.offer(root);
        int depth = 1;
        while (!q.isEmpty()) {
            int size = q.size();
            //将当前队列中的所有节点向四周扩散
            for (int i = 0; i < size; i++) {
                TreeNode cur = q.poll();
                //判断是否到达终点
                if (cur.left == null && cur.right == null) {
                    return depth;
                }
                //将cur的相邻节点加入队列
                if (cur.left != null) {
                    q.offer(cur.left);
                }
                if (cur.right != null) {
                    q.offer(cur.right);
                }
            }
            //在这里增加步数
            depth++;
        }
        return depth;
    }


    public int heightoftree(TreeNode root) {
        if (root == null) {
            return 0;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        int depth = 1;
        while (!queue.isEmpty()) {
            int size = queue.size();
            for (int i = 0; i < size; i++) {
                TreeNode cur = queue.poll();
                //看看当前节点的左右子树是不是为空
                if (cur.left == null && cur.right == null) {
                    return depth;
                }
                //左右子树不为空，继续加入队列中
                if (cur.left != null) {
                    queue.offer(cur.left);
                }
                if (cur.right != null) {
                    queue.offer(cur.right);
                }
            }
            depth++;
        }
        return depth;

    }
}